<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
        <span v-if="item.redirect === 'noRedirect' || index == levelList.length - 1" class="no-redirect">{{ item.meta?.title }}</span>
        <a v-else @click.prevent="handleLink(item)">{{ item.meta?.title }}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script lang="ts" setup>
import { ref, watchEffect } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { CustomRoute } from 'src/types/route';

/**
 * 获取当前路由对象
 */
const route = useRoute();

/**
 * 获取路由器实例
 */
const router = useRouter();

/**
 * 存储面包屑路径列表
 * @type {Ref<CustomRoute[]>}
 */
const levelList = ref<CustomRoute[]>([]);

/**
 * 获取面包屑路径
 */
function getBreadcrumb() {
  // 只显示具有 meta.title 的路由
  let matched = route.matched.filter(item => item.meta && item.meta.title) as CustomRoute[];
  const first = matched[0];

  // 判断是否为首页
  if (!isDashboard(first)) {
    matched = [{ path: '/index', meta: { title: '首页' } } as CustomRoute].concat(matched);
  }

  levelList.value = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false) as CustomRoute[];
}

/**
 * 判断是否为首页
 * @param {CustomRoute | undefined} route - 路由记录
 * @returns {boolean} - 是否为首页
 */
function isDashboard(route: CustomRoute | undefined): boolean {
  const name = route?.name;
  if (!name) {
    return false;
  }
  return name.trim() === 'Index';
}

/**
 * 处理链接点击事件
 * @param {CustomRoute} item - 路由记录
 */
function handleLink(item: CustomRoute) {
  const { redirect, path } = item;

  if (redirect && redirect !== 'noRedirect') {
    if (typeof redirect === 'string') {
      // 如果 redirect 是字符串
      router.push(redirect);
    } else if (typeof redirect === 'object') {
      // 如果 redirect 是对象
      router.push(redirect);
    } else if (typeof redirect === 'function') {
      // 如果 redirect 是函数
      const to = redirect(route); // 调用函数并传递当前路由
      router.push(to);
    }
    return;
  }

  router.push(path);
}

/**
 * 监听路由变化并更新面包屑
 */
watchEffect(() => {
  // 如果进入重定向页面，不更新面包屑
  if (route.path.startsWith('/redirect/')) {
    return;
  }
  getBreadcrumb();
});

// 初始化面包屑
getBreadcrumb();
</script>

<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>